package top.jiangqiang.qyblog.core.service.impl;

import org.springframework.stereotype.Service;
import top.jiangqiang.qyblog.common.base.response.Result;
import top.jiangqiang.qyblog.common.exception.JsonException;
import top.jiangqiang.qyblog.core.base.service.impl.BaseServiceImpl;
import top.jiangqiang.qyblog.core.domain.dto.LinkAddDto;
import top.jiangqiang.qyblog.core.domain.dto.LinkUpdateDto;
import top.jiangqiang.qyblog.core.domain.entity.Link;
import top.jiangqiang.qyblog.core.domain.vo.LinkVo;
import top.jiangqiang.qyblog.core.mapper.LinkMapper;
import top.jiangqiang.qyblog.core.service.ILinkService;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author JiangQiang
 * @since 2023-05-30
 */
@Service
public class LinkServiceImpl extends BaseServiceImpl<LinkMapper, Link> implements ILinkService {

    @Override
    public Result<LinkVo> getLink(Long id) {
        LinkVo linkVo = getById(id, LinkVo.class);
        if (linkVo == null) {
            return Result.error("友联不存在");
        } else {
            return Result.ok(linkVo);
        }
    }

    @Override
    public Result<LinkVo> editLink(LinkUpdateDto linkUpdateDto) {
        Long linkId = linkUpdateDto.getId();
        if (getById(linkId) == null) {
            throw new JsonException("友联不存在");
        }
        Link link = lambdaQuery().eq(Link::getLink, linkUpdateDto.getLink()).one();
        if (link != null && !link.getId().equals(linkId)) {
            throw new JsonException("友联地址不允许重复");
        }
        link = typeConverter.convert(linkUpdateDto, Link.class);
        baseMapper.updateById(link);
        return getLink(linkId);
    }

    @Override
    public Result<LinkVo> saveLink(LinkAddDto linkAddDto) {
        Link link = lambdaQuery().eq(Link::getLink, linkAddDto.getLink()).one();
        if (link != null) {
            throw new JsonException("友联地址已经存在");
        }
        link = typeConverter.convert(linkAddDto, Link.class);
        baseMapper.insert(link);
        return getLink(link.getId());
    }
}
